﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FanPages.Server.Services.Contracts;
using FanPages.Server.Repostory.EFRepository.Model;
using FanPages.Common.DataAccess;
using FanPages.Server.Services.Transformers;
using FanPages.Common.Exceptions;
using FanPages.Server.Services.Contracts.Dto;

namespace FanPages.Server.Services
{
    public class FixedLinkService : IFixedLinkService
    {
        IRepository<FixedLink> repository = new EFRepository<FixedLink>(new FanPagesEntities());

        public void Save(FixedLinkDto fixedLink)
        {
            try
            {
                if (fixedLink.Id != 0)
                {
                    var item = repository.First(x => x.Id == fixedLink.Id);
                    repository.Update(new FixedLinkTransformerSvc().ToExistingClient(fixedLink, item));
                }
                else
                {
                    repository.Add(new FixedLinkTransformerSvc().ToClient(fixedLink));
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException("FixedLinkService.Save exception", ex);
            }
        }

        public List<FixedLinkDto> GetByFanItem(FanItemDto fanItem)
        {            
            try
            {
                var newList = repository.Find(x => x.FanItem.Id == fanItem.Id).ToList();
                return new FixedLinkTransformerSvc().ToListDto(newList);
            }
            catch (Exception ex)
            {
                throw new ServiceException("FixedLinkService.GetByFanItem exception", ex);
            }
        }


        public void Delete(int id)
        {
            try
            {
                var item = repository.First(x => x.Id == id);
                repository.Delete(item);
            }
            catch (Exception ex)
            {
                throw new ServiceException("FixedLinkService.Delete exception", ex);
            }
        }

        public FixedLinkDto GetById(int id)
        {
            try
            {
                var item = repository.First(x => x.Id == id);
                return new FixedLinkTransformerSvc().ToDto(item);
            }
            catch (Exception ex)
            {
                throw new ServiceException("FixedLinkService.GetById exception", ex);
            }
        }
    }
}
